<template>
  <t-skeleton :loading="loading">
    <!-- 内容 -->
    <template v-if="contractDetails.id">
      <div style="margin-bottom: var(--td-comp-margin-s)">
        <t-button v-permission="['system:order-contract-zheng:update']" v-if="contractDetails.result !=2&&contractDetails.result !=1" @click="handleOpenDialog('update', { id: contractDetails.id })"> 编辑合同 </t-button>
        <t-button v-permission="['system:order-designer:zz-contract-approval']" v-if="contractDetails.result == null || contractDetails.result == 3 || contractDetails.result == 4" @click="handleApprove"> 发起审批 </t-button>
        <t-button v-permission="['system:order-contract-zheng:update-actual-time']" v-if="orderDetails.orderId&&(!contractDetails.actualBeginTime ||!contractDetails.actualEndTime)" @click="handleSaveActualTime"> 完善实际时间 </t-button>
        <span v-if="contractDetails.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(contractDetails.result - 1).theme">{{
          getTagThemeAndLabel(contractDetails.result - 1).label
        }}</t-tag>
      </span>
      </div>      
      <t-descriptions  bordered :column="4">
        <t-descriptions-item  v-if="contractDetails.id" :span="4">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同编号</span>
          </template>
           {{ contractDetails.contractNo }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>施工模板</span>
          </template>
          {{ stageModelName  }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>纯设计</span>
          </template>
          {{ dictionaryStore.analysis('is_type', contractDetails.isDesigner)  }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>是否有产品</span>
          </template>
          {{ dictionaryStore.analysis('is_type', contractDetails.isProduct)   }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同总价</span>
          </template>
          {{ contractDetails.contractPrice }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>签约时间</span>
          </template>
          {{ contractDetails.contractSigningTime?dayjs(contractDetails.contractSigningTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
        </t-descriptions-item>
        <t-descriptions-item v-if="['0'].includes(contractDetails.isDesigner)">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同开工时间</span>
          </template>
          {{ contractDetails.contractBeginTime?dayjs(contractDetails.contractBeginTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item v-if="['0'].includes(contractDetails.isDesigner)">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同完工时间</span>
          </template>
          {{ contractDetails.contractEndTime?dayjs(contractDetails.contractEndTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="实际开工时间" v-if="['0'].includes(contractDetails.isDesigner)">
          {{ contractDetails.actualBeginTime?dayjs(contractDetails.actualBeginTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="实际完工时间" v-if="['0'].includes(contractDetails.isDesigner)">
          {{ contractDetails.actualEndTime?dayjs(contractDetails.actualEndTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="合同文件" :span="4">
          <upload v-model:files="contractDetails.contractFile" multiple disabled />
        </t-descriptions-item>
        <t-descriptions-item label="备注" :span="4">{{ contractDetails.remark }}</t-descriptions-item>
        <t-descriptions-item label="赠品" :span="4">
       
          <div style="width: 100%">
              <t-table
                row-key="id"
                :data="contractDetails.gift"
                :columns="[
                  { colKey: 'name', align: 'center',title: '赠品名称'},
                  { colKey: 'fileUrl', align: 'center',title: '赠品图片'},
                  { colKey: 'money', align: 'center',title: '赠品价值金额'},
                ]"
                bordered
                size="small"
                stripe
                hover
                >
                  
                  <template #fileUrl="{ row }">
                    <image-viewer  :images="[row.fileUrl]" width="80px" height="80px" />
                  </template>
              </t-table>
            </div>
        </t-descriptions-item>
        <t-descriptions-item :span="4" v-if="['0'].includes(contractDetails.isDesigner)">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>分期付款</span>
          </template>
          <div style="width: 100%">
              <t-table
                row-key="id"
                :data="contractDetails.payList"
                :columns="[
                  { colKey: 'payNumber', align: 'center',title: '收款期数' },
                  { colKey: 'paymentStage',align: 'center', title: '收款阶段' },
                  { colKey: 'proportion', align: 'center',title: '收款比例(%)' },
                  { colKey: 'amountOfMoney', align: 'center',title: '期款金额(元)' },
                  { colKey: 'xjje',align: 'center', title: '洽商金额(元)' },
                  { colKey: 'reminderForCollectionStage', align: 'center',title: '收款提醒阶段',width:280 },
                ]"
                bordered
                hover
                size="small"
                stripe
                >
                <template #reminderForCollectionStage="{ row, rowIndex }">
                  <t-cascader
                  v-model:value="row.reminderForCollectionStage"
                  :options="stageTree"
                  :keys="{ value: 'id', label: 'stageName' }"
                  placeholder=""
                  filterable
                  clearable
                  :readonly="true"
                  class="text-only-cascader"

                />
                </template>
                  
                  <template #payStatus="{ row }">
                    {{ dictionaryStore.analysis('decoration_construction_order_stage', row.payStatus) }}
                  </template>
              </t-table>
            </div>
        </t-descriptions-item>
        
      </t-descriptions>


    </template>
    <!-- 空 -->
    <t-empty v-else style="margin: 100px">
      <template #action>
        <t-button
          v-permission="['system:order-contract-zheng:create']"
          @click="
            handleOpenDialog('create', {
              isDesigner: '0',
              isProduct: '1',
              orderId: orderId,
              orderType: orderDetails.orderType,
              contractFile: [],
              payList: [],
              gift:[]
            })
          "
        >
          新建合同
        </t-button>
      </template>
    </t-empty>
    <!-- 自定义对话框 -->
    <contract-dialog ref="customDialogRef" @request-success="handleDialogRequestSuccess" :company-id="orderDetails.companyId" />
    <contract-actual-dialog ref="customActualDialogRef" @request-success="handleDialogRequestSuccess" />
  </t-skeleton>
    <!-- 粘性审批对话框 -->
    <sticky-approve-dialog ref="stickyApproveDialogRef8" :order-id="orderDetails.id" approve-type="8" />
    <sticky-approve-dialog ref="stickyApproveDialogRef15" :order-id="orderDetails.id" approve-type="15" />
    <!-- 发起人 -->
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog1Style"  ref="stickyInitApproveDialogRef8" :order-id="orderDetails.orderId || orderDetails.id" approve-type="8" />
  <sticky-init-approve-dialog :is-multiple="isMultiple" :style="dialog2Style" ref="stickyInitApproveDialogRef15" :order-id="orderDetails.orderId || orderDetails.id" approve-type="15" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import { getContractByOrderId, orderContractZhengCRUD, zzContractApproval } from '@/api/finance/contract';
import { engineeringConfigCRUD, engineeringModelCRUD } from '@/api/config/common-config';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import StickyInitApproveDialog from '@/pages/approve/components/sticky-init-approve-dialog.vue';
import listToTree from '@/utils/listToTree';
import { useDictionaryStore } from '@/store';

import ContractDialog from './ContractDialog.vue';
import ContractActualDialog from './ContractActualDialog.vue';

interface TagThemeAndLabel {
  theme: 'warning' | 'success' | 'danger' | 'default';
  label: string;
}

// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'orderDetails',
  },
});
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 将原有的 orderDetails 替换为 details
const orderDetails = details;

const orderId = details.value.orderId || details.value.id
console.log(orderId,'orderid');
// 施工模板模板列表
const stageModelOptions = ref([]);
// 处理获取施工模板模板列表
const handleGetstageModelOptions = () => {
  const params = {
    // companyId: orderDetails.value.companyId,
    pageSize: -1,
  };
  engineeringModelCRUD.page(params).then((data) => {
    stageModelOptions.value = data.list;
  });
};
handleGetstageModelOptions();
// 计算属性，用于查找匹配的stageModel名称
const stageModelName = computed(() => {
  if (!contractDetails.value.stageModelId || stageModelOptions.value.length === 0) {
    return '';
  }
  const found = stageModelOptions.value.find(
    item => item.id === contractDetails.value.stageModelId
  );
  return found ? found.name : contractDetails.value.stageModelId;
});
// // 订单详情
// const orderDetails = inject<Ref<Record<string, any>>>('orderDetails');
// 加载状态
const loading = ref(false);
// 合同详情
const contractDetails = ref<Record<string, any>>({});
// 整装合同id
const zzContractId = ref()
// 精简节点树
const stageTree = ref([]);
// 处理获取精简节点
const handleGetSimpleStageTree = () => {
  const params = {
    pageSize:-1
  }
  engineeringConfigCRUD.page(params).then((data) => {
    stageTree.value = listToTree(data.list);
  });
};
handleGetSimpleStageTree();
// 处理获取合同详情
const handleGetContractDetails = () => {
  loading.value = true;
  const params = {
    orderId: orderId,
  };
  getContractByOrderId(params)
    .then((data) => {
      // if (data) contractDetails.value = data.list[0] || {};
      if(data.total>0) {
        zzContractId.value = data.list[0].id
        handleGetContractZheng({id:data.list[0].id})
      } else {
        contractDetails.value={}
      } 
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loading.value = false;
    });
};
handleGetContractDetails();
const handleGetContractZheng = (params:Record<string,any>) =>{
  orderContractZhengCRUD.get(params).then(res=>{
    contractDetails.value=res
    console.log(contractDetails.value,'pppp');
    
  })
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
const customActualDialogRef = useTemplateRef('customActualDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleGetContractDetails();
  if (result.mode === 'update') handleGetContractDetails();
};
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: number): TagThemeAndLabel => {
  const map: TagThemeAndLabel[] = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 发起审批
const handleApprove = () =>{
  const params = {
    orderId:orderId,
    logType:'contract'
  }
  zzContractApproval(params).then(res => {
    MessagePlugin.success('成功发起审批');
    handleGetContractZheng({id:zzContractId.value})
  }).catch(({ message }) => {
      MessagePlugin.error(message);
    })
    
}
interface DialogRef {
  visible: boolean;
  open: () => void;
  close: () => void;
}
// 粘性审批对话框ref
const stickyApproveDialogRef8 = useTemplateRef('stickyApproveDialogRef8');
const stickyApproveDialogRef15 = useTemplateRef('stickyApproveDialogRef15');
const stickyInitApproveDialogRef15 = ref<DialogRef | null>(null);
const stickyInitApproveDialogRef8 = ref<DialogRef | null>(null);

onMounted(() => {
  const { approveType } = orderDetails.value;
  if (approveType === '8')   stickyApproveDialogRef8.value.open();
  if (approveType === '15')  stickyApproveDialogRef15.value.open();
  stickyInitApproveDialogRef8.value.open();
  stickyInitApproveDialogRef15.value.open();
});
// 判断是否同时显示多个对话框
const isMultiple = computed<boolean>(() => {  
  return stickyInitApproveDialogRef15.value?.visible && stickyInitApproveDialogRef8.value?.visible;
});

// 第一个对话框的样式
const dialog1Style = computed(() => {
  if (isMultiple.value) {
    return { left: '40%' }; // 多个对话框时，第一个对话框靠左
  }
  return {}; // 单个对话框时，样式不变
});

// 第二个对话框的样式
const dialog2Style = computed(() => {
  if (isMultiple.value) {
    return { left: '60%' }; // 多个对话框时，第二个对话框靠右
  }
  return {}; // 单个对话框时，样式不变
});
const handleSaveActualTime = () => {
  const params = {
    id:contractDetails.value.id,
    actualBeginTime:contractDetails.value.actualBeginTime,
    actualEndTime:contractDetails.value.actualEndTime
  }
  customActualDialogRef.value.open('update', params);
}
</script>

<style lang="less" scoped>
.text-only-cascader {
  :deep(.t-input__suffix-icon) {
    display: none;
  }
  
}
</style>
